import org.jsoup.Connection;
import org.jsoup.Jsoup;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

public class Baidu_pic implements Runnable{
    ArrayList<String> list;
    HashMap<String,String> header;
    public Baidu_pic(ArrayList<String> list,HashMap<String,String> header){
        this.list=list;
        this.header=header;
    }
    public void run(){
        File dir = new File(new Date().getTime()+"");
        dir.mkdir();
        System.out.println("启动线程:"+Thread.currentThread().getName()+",开始下载图片");
        int i=0;
        for (String str : list){
            Connection connect = Jsoup.connect(str);
            Connection conheader=connect.headers(header);
            Connection.Response response;
            try {
                response = conheader.method(Connection.Method.GET).ignoreContentType(true).execute();
            } catch (IOException ex) {
                System.out.println("爬虫连接出错");
                ex.printStackTrace();
                break;
            }
            BufferedInputStream stream = response.bodyStream();
            byte[] buffer = new byte[1024];
            int len;
            try {
                FileOutputStream fileout = new FileOutputStream(new File(dir, String.valueOf(i++)+".jpg"));
                BufferedOutputStream out = new BufferedOutputStream(fileout);
                while ((len=stream.read(buffer))!=-1){
                    out.write(buffer,0,len);
                }
                out.flush();
                out.close();
            } catch (Exception ex) {
                System.out.println("保存文件出错");
                ex.printStackTrace();
            }
        }
        System.out.println("任务:"+Thread.currentThread().getName()+"结束,下载成功");
    }
}
